﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1.Test
{
    internal class Class7
    {
        public static void Test70()
        {
            if (null != "1")
            {

            }

        }

        static void Test69()
        {
            try
            {
                var a = 1;
                var b = 0;
                var c = a / b;
            }
            catch (Exception ex)
            {
                string demystifiedStackTrace = ex.ToStringDemystified();
                XTrace.WriteLine(demystifiedStackTrace);
            }
        }
        static void Test68()
        {
            var list1 = new List<Student>();

            while (true)
            {
                for (int i = 1; i <= 100; i++)
                {
                    list1.Add(new Student()
                    {
                        Id = DateTime.UtcNow.Ticks,
                        Name = DateTime.Now.ToString("yyyyMMddHHmmssfff"),
                        Age = i
                    });
                }

                foreach (var item in list1)
                {
                    XTrace.WriteLine(item.ToJsonString());
                }

                Thread.Sleep(2000);
            }

        }

        static void Test67()
        {
            var list1 = new List<Student>() { new Student() { Id = 1, Name = "A", Age = 31 }, new Student() { Id = 2, Name = "B", Age = 32 } };

            while (true)
            {
                var list2 = list1.Where(A => A.Id >= 2);

                foreach (var item in list2)
                {
                    item.Name = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                }

                XTrace.WriteLine(list1.ToJson());

                XTrace.WriteLine(list2.ToJson());
                Thread.Sleep(2000);
            }

        }

        const string token = "EW55IFNMj3QTANR5T2ORt-pOrXH6raQId7KlCgjMvN4G3FeIBTkXwXwWwEMlWqcZIO8nYNM-p26bm941i_LhNQ==";
        const string bucket = "IOT";
        const string org = "HISENSE";

        static void Test66()
        {
            object a = 88888888888888888;

            Object b = Convert.ToUInt16(a);

            object obj = (UInt16)1;

            obj.ToString();

            if (obj is ushort)
            {
                ushort uintValue = (ushort)obj;
                Console.WriteLine("ushort 转换成功: " + uintValue);
            }
            else if (obj is uint)
            {
                uint uintValue = (uint)obj;
                Console.WriteLine("uint 转换成功: " + uintValue);
            }
            else if (obj is int && (int)obj >= 0 && (int)obj <= uint.MaxValue)
            {
                uint uintValue = (uint)(int)obj;
                Console.WriteLine("int 转换成功: " + uintValue);
            }
            else if (obj is long && (long)obj >= 0 && (long)obj <= uint.MaxValue)
            {
                uint uintValue = (uint)(long)obj;
                Console.WriteLine("uint 转换成功: " + uintValue);
            }
            else if (obj is string && uint.TryParse((string)obj, out uint parsedValue))
            {
                Console.WriteLine("string 转换成功: " + parsedValue);
            }
            else
            {
                throw new ArgumentException("无法将对象转换为uint类型");
            }
        }
        static void Test65()
        {
            //Option 1: Use InfluxDB Line Protocol to write data
            const string data = "mem,host=host1 used_percent=23.43234543";
            using (var client = new InfluxDBClient("http://localhost:8086", token))
            {
                using (var writeApi = client.GetWriteApi())
                {
                    writeApi.WriteRecord(data, WritePrecision.Ns, bucket, org);
                }
            };


            //Option 2: Use a Data Point to write data
            var point = PointData
                .Measurement("mem")
                .Tag("host", "host1")
                .Field("used_percent", 23.43234543)
                .Timestamp(DateTime.UtcNow, WritePrecision.Ns);

            using (var client = new InfluxDBClient("http://localhost:8086", token))
            {
                using (var writeApi = client.GetWriteApi())
                {
                    writeApi.WritePoint(point, bucket, org);
                }
            };

            //Option 3: Use POCO and corresponding class to write data
            var mem = new Mem { Host = "Cluee", UsedPercent = 23.43234543, Time = DateTime.UtcNow };
            using (var client = new InfluxDBClient("http://localhost:8086", token))
            {
                using (var writeApi = client.GetWriteApi())
                {
                    writeApi.WriteMeasurement(mem, WritePrecision.Ns, bucket, org);
                }
            };
        }



        static void Test64()
        {
            var interpreter = new Interpreter();

            var result6 = interpreter.Eval<decimal>("(19684-6553)/26214d*202-101");


            XTrace.WriteLine($"1^1={result6.ToString()}");

            return;

            var result5 = interpreter.Eval<decimal>("1^1");
            XTrace.WriteLine($"1^1={result5.ToString()}");

            var result4 = interpreter.Eval<decimal>("1^1");
            XTrace.WriteLine($"1^1={result4.ToString()}");

            var result3 = interpreter.Eval<decimal>("0^1");
            XTrace.WriteLine($"0^1={result3.ToString()}");

            var result2 = interpreter.Eval("1==1");
            XTrace.WriteLine($"1==1={result2.ToString()}");

            var result1 = interpreter.Eval("~1");
            XTrace.WriteLine($"~1={result1.ToString()}");

            for (int i = 0; i <= 1000; i++)
            {
                var express = $"{i}*0.1";
                var result0 = interpreter.Eval<decimal>(express);

                XTrace.WriteLine($"{express}={result0}");

                //var express2 = $"{i}^1";
                //var result5 = interpreter.Eval(express2);
                //XTrace.WriteLine($"{express2}={result5.ToString()}");
            }


        }

        static void Test63()
        {
            //var str1 = $"{(char)1B}";

            var bytes = HexStringToByteArray("1B");
            XTrace.WriteLine("");
        }
        static void Test62()
        {
            // 获取当前的 UTC 时间  
            DateTime utcNow = DateTime.UtcNow;

            // 将 DateTime 转换为 Unix 时间戳（秒）  
            long timestamp = ((DateTimeOffset)utcNow).ToUnixTimeSeconds();

            Console.WriteLine($"1-UTC 时间: {utcNow}");
            Console.WriteLine($"1-LOCAL 时间: {utcNow.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss")}");
            Console.WriteLine($"1-Unix 时间戳: {timestamp}");

            // 将时间戳转换为DateTimeOffset对象（UTC时间）  
            DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(timestamp);

            // 如果需要本地时间，可以将DateTimeOffset转换为DateTime，并指定本地时区  
            // 注意：这里使用的是本地时区，可能会受到系统时区设置的影响  
            DateTime localTime = dateTimeOffset.LocalDateTime;

            // 如果需要UTC时间，可以直接使用DateTimeOffset的UtcDateTime属性  
            DateTime utcTime = dateTimeOffset.UtcDateTime;

            // 输出结果  
            Console.WriteLine("2-UTC时间: " + utcTime.ToString("yyyy-MM-dd HH:mm:ss"));
            Console.WriteLine("2-本地时间: " + localTime.ToString("yyyy-MM-dd HH:mm:ss"));
        }

        static void Test61()
        {
            // 字符串转HEX示例  
            string originalString = "号";
            string resultHex = StringToHex(originalString);
            Console.WriteLine(resultHex); // 输出: 48656c6c6f20576f726c64  

            // HEX转字符串示例  
            string hexString = "BAC5";
            string resultString = HexToString(hexString);
            Console.WriteLine(resultString); // 输出: Hello World  

            string hexString2 = "1B0B00000099990104A9224EA4FD1B"; // "Hello World" 的 HEX 表示  
            byte[] byteArray = HexStringToByteArray(hexString2);
            string resultString2 = Encoding.UTF8.GetString(byteArray);
            Console.WriteLine(resultString2); // 输出 "Hello World"  
        }

        // 上面的HexToString方法保持不变  
        static string StringToHex(string str)
        {
            // 将字符串转换为字节数组（使用UTF8编码）  
            //byte[] bytes = Encoding.UTF8.GetBytes(str);

            // 注册 GBK 编码  
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            byte[] bytes = Encoding.GetEncoding("GBK").GetBytes(str);

            // 创建一个StringBuilder来存储HEX字符串  
            StringBuilder sb = new StringBuilder(bytes.Length * 2);

            // 遍历字节数组，将每个字节转换为HEX并添加到StringBuilder中  
            foreach (byte b in bytes)
            {
                sb.AppendFormat("{0:x2}", b);
            }

            return sb.ToString().ToUpper();
        }

        static string HexToString(string hex)
        {
            // 确保hex字符串长度为偶数  
            if (hex.Length % 2 != 0)
            {
                throw new ArgumentException("Invalid hex string length.");
            }

            // 将HEX字符串转换为字节数组  
            byte[] bytes = Convert.FromHexString(hex);

            // 将字节数组转换为字符串（使用UTF8编码）  
            //string str = Encoding.UTF8.GetString(bytes);

            string str = Encoding.GetEncoding("GBK").GetString(bytes);
            return str;
        }

        static byte[] HexStringToByteArray(string hex)
        {
            int NumberChars = hex.Length;
            byte[] bytes = new byte[NumberChars / 2];
            for (int i = 0; i < NumberChars; i += 2)
            {
                bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
            }
            return bytes;
        }
    }
}
